from threading import Thread
import socket
import json
import time as stime
from queue import Queue
from django.http import JsonResponse
from app.models import datas, trace
import math


class CarServer():
    def __init__(self):
        self.client_connect_pool = {}  # 用户连接池  sock:client
        self.clients = {}
        self.direction = [0, 0, 0, 0]
        self.timestamp = 0
        self.angle = 0.0
        self.__init_server__()

    def __init_server__(self):
        self.socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # self.socket_server.bind(('192.168.126.166', 11111))
        self.socket_server.bind(('172.20.10.10', 12345))
        # self.socket_server.bind(('172.20.10.3', 11111))
        # self.socket_server.bind(('172.27.236.76', 11111))
        # self.socket_server.bind(('172.27.238.75', 11111))
        self.socket_server.listen(5)
        print("开启")
        print("Server start,waiting for client connecting...")

    #   处理车发送的数据
    def __handle_car_connect__(self, client, sock):
        print(sock, 'connect')
        while (True):
            recv = client.recv(5000)
            # print(recv)
            message_json = json.loads(recv.decode(encoding='utf8'))
            # print(message_json)
            content = message_json['content']
            content = json.loads(content)
            data_list = content['data_list']
            trace_stack = content['trace_stack']
            if trace_stack:  # 路径不为空
                # print(trace_stack)
                # print(type(trace_stack))
                for _ in range(len(trace_stack)):
                    trace_stack[_] = json.loads(trace_stack[_])
                    # print(trace_stack[_])
                    # print(type(trace_stack[_]))
                    if 1 in self.direction:  # 当前存的运动数组
                        print('1')
                        if 1 in trace_stack[_]['direction']:  # 最新为运动数组
                            #   直接覆盖
                            print('error')
                            self.direction = trace_stack[_]['direction']
                            self.timestamp = trace_stack[_]['timestamp']
                            print(self.direction, self.timestamp)
                            print(type(self.direction), type(self.timestamp))
                        else:  # 最新为停止数组
                            if self.direction[0] == 1:  # 上
                                time = trace_stack[_]['timestamp'] - self.timestamp
                                print('上', time)
                                longth = int(time * 20)
                                x = longth * math.sin(self.angle)
                                y = longth * math.cos(self.angle)
                                print(x, y)
                                #   存入数据库
                                t = trace(x=int(x), y=int(y), pi=sock[0])
                                t.save()
                            elif self.direction[1] == 1:  # 下
                                time = trace_stack[_]['timestamp'] - self.timestamp
                                print('下', time)
                                longth = int(time * 20)
                                x = - longth * math.sin(self.angle)
                                y = - longth * math.cos(self.angle)
                                print(x, y)
                                #   存入数据库
                                t = trace(x=int(x), y=int(y), pi=sock[0])
                                t.save()
                            elif self.direction[2] == 1:  # 左
                                time = trace_stack[_]['timestamp'] - self.timestamp
                                print('左', time)
                                self.angle = self.angle - (109.1 * time)
                                print(self.angle)
                            elif self.direction[3] == 1:  # 右
                                time = trace_stack[_]['timestamp'] - self.timestamp
                                print('右', time)
                                self.angle = self.angle + 109.1 * time
                                print(self.angle)

                            #   计算完后更新
                            self.direction = trace_stack[_]['direction']
                            self.timestamp = trace_stack[_]['timestamp']
                            print(self.direction, self.timestamp)
                            print(type(self.direction), type(self.timestamp))

                    elif 1 not in self.direction:  # 当前存的停止数组
                        print('0')
                        #   直接覆盖
                        self.direction = trace_stack[_]['direction']
                        self.timestamp = trace_stack[_]['timestamp']
                        print(self.direction, self.timestamp)
                        print(type(self.direction), type(self.timestamp))

            if data_list:  # 环境数据不为空
                #   存入数据库
                data = datas(data=float(data_list[0]), time=stime.strftime("%Y-%m-%d %X"), pi=sock[0])
                data.save()

    #   封装控制字段
    def __generate_package__(self, content, pac_type, ctl_type, carIP):
        packge = {}
        packge['src_id'] = "172.20.10.10"  # 本机ip地址
        packge['dst_id'] = carIP
        packge['pac_type'] = pac_type
        packge['ctl_type'] = ctl_type
        packge['timestamp'] = stime.strftime("%Y-%m-%d %X")
        packge['content'] = content
        return packge

    #   发送报文
    def __sending_package__(self, package, ip):
        if ip in self.client_connect_pool.keys():
            client = self.client_connect_pool[ip]
            # print(package)
            client.send(json.dumps(package).encode('utf8'))

    def run_server(self):
        while True:
            client, sock = self.socket_server.accept()
            self.client_connect_pool[sock[0]] = client
            #   当有连接时，开启一个新线程用于处理
            thread = Thread(target=self.__handle_car_connect__, args=(client, sock))
            thread.setDaemon(True)
            thread.start()